<?php
$host = '0.0.0.0';
$port = 6666;
$listen_socket = socket_create( AF_INET, SOCK_STREAM, SOL_TCP );
socket_set_option( $listen_socket, SOL_SOCKET, SO_REUSEADDR, 1 );
socket_set_option( $listen_socket, SOL_SOCKET, SO_REUSEPORT, 1 );
socket_bind( $listen_socket, $host, $port );
socket_listen( $listen_socket );
socket_set_nonblock( $listen_socket );
$client = array( $listen_socket );
while ( true ) {
    $read      = $client;
    $write     = array();
    $exception = array();
    $ret       = socket_select( $read, $write, $exception, NULL );
    if ( $ret <= 0 ) {
        continue;
    }
    // 就是说，如果 listen-socket 中有事件，listen-socket能有啥事件：就是用新的客户端来了
    if ( in_array( $listen_socket, $read ) ) {
        $connection_socket = socket_accept( $listen_socket );
        if ( !$connection_socket ) {
            continue;
        }
        $client[] = $connection_socket;
        $key    = array_search( $listen_socket, $read );
        unset( $read[ $key ] );
    }
    // 对于其他socket
    foreach( $read as $read_key => $read_fd ) {
        socket_recv( $read_fd, $recv_content, 1024, 0 );
        if ( !$recv_content ) {
            unset( $client[ $read_key ] );
            socket_close( $read_fd );
            continue;
        }
        echo $recv_content;
        unset( $client[ $read_key ] );
        socket_shutdown( $read_fd );
        socket_close( $read_fd );
    }
}